package com.zhangye.test.controller;

import java.io.IOException;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.zhangye.test.model.Admin;
import com.zhangye.test.model.AdminRoles;
import com.zhangye.test.model.AdminUserRoles;
import com.zhangye.test.model.SmsSession;
import com.zhangye.test.util.Base64;
import com.zhangye.test.util.Result;


/**
 * 张叶，登录
 * @author Administrator
 *
 */
@Controller
@RequestMapping("login")
public class LoginController  extends  BaseController{
	
	
	/**
	 * 登录
	 * 作者： 张叶
	 * 创建时间：2018年5月23日  上午11:32:11
	 */
	@RequestMapping("/index")
	public String toLoginPage(HttpServletRequest request,HttpServletResponse response) throws IOException{
		return "login";
	}
	/**
	 * 公钥
	 * 作者：张叶
	 * 创建时间：2016年8月18日 下午2:00:17
	 */
	@RequestMapping(value = "/publicKey", method = RequestMethod.POST)
	public @ResponseBody Map<String, String> publicKey(HttpServletRequest request) {
		RSAPublicKey publicKey = rsaService.generateKey(request);
		Map<String, String> data = new HashMap<String, String>();
		data.put("modulus", Base64.encode(publicKey.getModulus().toByteArray()));
		data.put("exponent", Base64.encode(publicKey.getPublicExponent().toByteArray()));
		return data;
	}

	
	/**
	 * 修改密码
	 * 作者： 张叶
	 * 创建时间：2018年5月31日  上午10:23:44
	 */
	@ResponseBody
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    public Result updatePassword(HttpServletRequest request,RedirectAttributes redirectAttributes) {

    	String password = rsaService.decryptParameter("password", request);
    	String mobile = rsaService.decryptParameter("mobile", request);
    	String captcha = rsaService.decryptParameter("captcha", request);
    	rsaService.removePrivateKey(request);
    	Result result = new Result();
	    if (mobile != null && mobile != "" && captcha != null && captcha != "") {
			SmsSession ss = smsSessionService.findBySessionId(mobile);
			Admin admin = adminService.findByTelphone(mobile);
//			int reInt;
			if(admin != null){
				if (ss != null) {
//					try {
//						reInt = smsService.verifySMSCode(ss.getSessionId(), captcha);
//						if (reInt == 0) {
						if(captcha.equals(ss.getSessionId())){
							admin.setPassword(DigestUtils.md5Hex(password));
							int count = adminService.updateAdmin(admin, 0);
							if (count > 0) {
						        result.setCode(0);
						        result.setMessage("修改成功！");
							} else {
						        result.setCode(1);
						        result.setMessage("系统错误，修改失败！");
							}
						} else {
					        result.setCode(1);
					        result.setMessage("验证码错误!");
						}
//					} catch (Exception e) {
//						e.printStackTrace();
//					}
				} else {
			        result.setCode(2);
			        result.setMessage("验证码错误!");
				}
			}else{
		        result.setCode(3);
		        result.setMessage("当前用户不存在");
			}
		}else{
	        result.setCode(0);
	        result.setMessage("手机号或验证码不能为空!");
		}
	    return result;
    }
	    
	
	
	/**
	 * 登录
	 * 作者： 张叶
	 * 创建时间：2018年5月31日  上午9:36:41
	 */
	//增加了参数：用户类型
	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public Result login(String enuserName, String enPassword, RedirectAttributes redirectAttributes,
			HttpServletRequest request, Model model) {
		Result result = new Result();
		result.code = 0;
		// 获取账号密码
		String password = rsaService.decryptParameter("enPassword", request);
		String userName = rsaService.decryptParameter("enuserName", request);
		Admin admin = new Admin();
    	rsaService.removePrivateKey(request);
    	admin.setPassword(DigestUtils.md5Hex(password));
    	admin.setTelphone(userName);
        Subject currentUser = SecurityUtils.getSubject();
    	UsernamePasswordToken token = new UsernamePasswordToken(admin.getTelphone(), admin.getPassword(), true);

		try {
			// 使用权限工具进行用户登录，登录成功后跳到shiro配置的successUrl中，与下面的return没什么关系！
			currentUser.login(token);
		}  catch (UnknownAccountException uae) {
			redirectAttributes.addFlashAttribute("message", "未知账户");
			result.message = "未知账户";
			return result;
		} catch (IncorrectCredentialsException ice) {
			redirectAttributes.addFlashAttribute("message", "用户名或密码不正确");
			result.message = "用户名或密码不正确";
			return result;
		} catch (LockedAccountException lae) {
			redirectAttributes.addFlashAttribute("message", "账户已锁定");
			result.message = "账户已锁定";
			return result;
		} catch (ExcessiveAttemptsException eae) {
			redirectAttributes.addFlashAttribute("message", "用户名或密码错误次数过多");
			result.message = "用户名或密码错误次数过多";
			return result;
		} catch (AuthenticationException ae) {
			// 通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
			ae.printStackTrace();
			redirectAttributes.addFlashAttribute("message", "用户名或密码不正确");
			result.message = "用户名或密码不正确";
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			result.message =  "系统异常";
			return result;
        }

		// 验证是否登录成功
		if (currentUser.isAuthenticated()) {
			//登录成功后将用户名存入session
			Admin ad = (Admin) currentUser.getSession().getAttribute("currentUser");// 登录会员
			AdminUserRoles ar = adminUserRolesService.findByAdminId(ad.getId());// 获取会员角色权限关系
			if (ar != null) {
				AdminRoles aur = adminRolesService.findById(ar.getAurRolesid());// 获取会员角色
				redirectAttributes.addFlashAttribute("name", admin.getRealname());// 用户名
				redirectAttributes.addFlashAttribute("role", aur.getArName()); // 角色
			}

			result.code = 1;
		} else {
			token.clear();
		} 
		return result;
	}

	
    /**
     * 忘记密码
     * 作者： 张叶
     * 创建时间：2018年5月28日  下午4:03:35
     */
    @RequestMapping(value = "/forgetPwd")
    public String forgetPwd(){
    	return "forgetPwd";
    }
    
}
 